$(function () {
    $('#link_reg').on('click', function () {
        $('.login-box').hide()
        $('.reg-box').show()
    })
    $('#link_login').on('click', function () {
        $('.login-box').show()
        $('.reg-box').hide()
    })
    const form = layui.form
    const layer = layui.layer
    form.verify({
        pwd: [
            /^[\S]{6,12}$/
            , '密码必须6到12位，且不能出现空格'
        ],
        repwd: function (value) {
            let pwd = $('.reg-box [name=password]').val()
            if (pwd != value) {
                return '两次密码不一致'
            }
        }

    })
    $('#form_reg').on('submit', function (e) {
        e.preventDefault()
        const data = {
            username: $('#form_reg [name=username]').val(),
            password: $('#form_reg [name=password]').val(),
            repassword: $('#form_reg [name=repassword]').val()
        }
        $.ajax({
            method: 'POST',
            url: '/api/reguser',
            data,
            success(res) {
                if (res.status != 0) {
                    return layer.msg(res.message)
                } else {
                    layer.msg('注册成功')
                    $('#link_login').click()
                }
            }
        })
    })
    $('#form_login').submit(function (e) {
        e.preventDefault()
        $.ajax({
            method: 'POST',
            url: '/api/login',
            data: $(this).serialize(),
            success(res) {
                if (res.status !== 0) {
                    return layer.msg('登录失败')
                }
                layer.msg('登录成功')
                setStorage('token', res.token)
                location.href ='/index.html'
            }

        })

    })
})